<template>
  <div class="service-manage" v-loading="loadingPage">
    <div class="service-manage-edit-footer" v-show="!loadingPage">
      <div class="flex align-items-center service-title">{{ title }}</div>
      <div class="flex-x">
        <div class="overHideCon-1 mar-r-12" v-if="haveUserNote">
          <el-checkbox v-model="createNeedNote">{{$t('department.label.label5')}}</el-checkbox>
          
          <el-tooltip class="item" effect="dark" :content="$t('department.label.tips1')" placement="bottom">
            <i class="iconfont icon-question-circle mar-l-5 font-15-i"></i>
          </el-tooltip>
          
        </div>
        <FormCellChange
          class="mar-r-8"
          :count="formCellCount"
          @update="
            e => {
              formCellCount = e;
            }
          "
        ></FormCellChange>
        <el-button type="plain-third" :disabled="disabled" @click="cancel">{{ $t('common.base.cancel') }}</el-button>
        <el-button :disabled="disabled" type="primary" @click="saveEngineer">{{ $t('common.base.save') }} </el-button>
      </div>
    </div>
    <div class="service-manage-edit" v-show="!loadingPage">
      <div class="service-manage-edit-main" :class="formCellCount > 1 ? 'bbx-form-cell-box bbx-normal-form-builder-cell' : ''">
        <form-builder ref="form" class="bbx-cell-form-builder" :form-cell-count="formCellCount" :form-status="id ? 'edit' : 'new'" :fields="formField" :value="providerValue" :extra-validations="extraValidations" mode="service_engineer_edit" @update="update">
          <!--工程师编号-->
          <template slot="engineerCode" slot-scope="{ field, value }">
            <form-item ref="engineerCode" :label="field.displayName" class="bbx-form-cell-item" :prop-field="field" :prop-value="providerValue.engineerCode" :validation="extraValidations.engineerCode">
              <form-text :field="field" v-model="providerValue[field.fieldName]" :placeholder="field.placeholder || ''" @update="update" />
            </form-item>
          </template>
          <!--所属服务商-->
          <template slot="provider" slot-scope="{ field, value }">
            <form-item v-if="editEngineer" class="bbx-form-cell-item" :label="field.displayName" :is-not-null="!field.isNull">
              <div class="form-servicerNo">{{ value.name }}</div>
            </form-item>
            <form-item v-else ref="provider" class="bbx-form-cell-item" :label="field.displayName" :prop-field="field" :prop-value="providerValue.provider" :validation="extraValidations.provider">
              <biz-remote-select v-model="providerValue[field.fieldName]" :field="field" cleared :remote-method="fetchProviderType" :placeholder="!field.isNull ? `[${$t('common.base.isRequire')}]${field.placeHolder}` : field.placeHolder" :computed-width-keys="['name']" :inputDisabled="isProviderUser" @input="updateProvider">
                <div class="customer-template-option" slot="option" slot-scope="{ option }">
                  <span>{{ option.name }}</span>
                </div>
              </biz-remote-select>
            </form-item>
          </template>
          <!--性别-->
          <template slot="sex" slot-scope="{ field, value }">
            <form-item v-show="showSex" ref="sex" class="bbx-form-cell-item" :label="field.displayName" :prop-field="field" :prop-value="providerValue.sex" :validation="extraValidations.sex">
              <el-radio-group v-model="providerValue[field.fieldName]" :disabled="providerValue['idCardType'] === '身份证'">
                <el-radio v-for="item in field.setting.dataSource" :key="item" :label="item">{{ item }}</el-radio>
              </el-radio-group>
            </form-item>
          </template>
          <!--授权地址-->
          <template slot="authorizeAddress" slot-scope="{ field, value }">
            <form-item ref="authorizeAddress" class="bbx-form-item bbx-form-item-view-padding" :label="field.displayName" :prop-field="field" :prop-value="providerValue.authorizeAddress" :validation="extraValidations.authorizeAddress">
              <div class="bbx-table-new">
                <el-button icon="el-icon-plus" class="add-subform-btn" @click="addAddress">{{ $t('common.base.addArea') }} </el-button>
                <el-table header-row-class-name="common-list-table-header__v2" :data="providerValue[field.fieldName]" :border="true" max-height="250" style="width: 100%">
                  <el-table-column prop="province" :label="`${$t('common.base.province')}/${$t('common.base.municipality')}`" />
                  <el-table-column prop="city" :label="`${$t('common.base.district')}/${$t('common.base.town')}`" />
                  <el-table-column prop="dist" :label="`${$t('common.base.district')}/${$t('common.base.prefecture')}`" />
                  <el-table-column :label="$t('common.base.operation')">
                    <template slot-scope="scope">
                      <div class="color-primary just-cur-point" @click="removeChooseAddress(scope)">{{ $t('common.base.delete') }}</div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </form-item>
          </template>
          <!--授权工单类型-->
          <template slot="authorizeTask" slot-scope="{ field, value }">
            <form-item ref="authorizeTask" class="bbx-form-cell-item" :label="field.displayName" :prop-field="field" :prop-value="providerValue.authorizeTask" :validation="extraValidations.authorizeTask">
              <biz-remote-select v-model="providerValue[field.fieldName]" :field="field" :multiple-limit="10" multiple cleared :remote-method="fetchTaskType" :placeholder="!field.isNull ? `[${$t('common.base.isRequire')}]${field.placeHolder}` : field.placeHolder" :computed-width-keys="['name']">
                <div class="customer-template-option" slot="option" slot-scope="{ option }">
                  <span>{{ option.name }}</span>
                </div>
              </biz-remote-select>
            </form-item>
          </template>
          <!--授权产品目录-->
          <template slot="authorizeProduct" slot-scope="{ field, value }">
            <form-item ref="authorizeProduct" class="bbx-form-cell-item" :label="field.displayName" :prop-field="field" :prop-value="providerValue.authorizeProduct" :validation="extraValidations.authorizeProduct">
              <biz-remote-select v-model="providerValue[field.fieldName]" :field="field" :multiple-limit="10" multiple cleared :remote-method="fetchProductType" :placeholder="!field.isNull ? `[${$t('common.base.isRequire')}]${field.placeHolder}` : field.placeHolder" :computed-width-keys="['label']">
                <div class="customer-template-option" slot="option" slot-scope="{ option }">
                  <span>{{ option.name }}</span>
                </div>
              </biz-remote-select>
            </form-item>
          </template>
          <!--角色-->
          <template slot="role" slot-scope="{ field, value }">
            <form-item ref="role" class="bbx-form-cell-item" :label="field.displayName" :prop-field="field" :prop-value="providerValue.role" :validation="extraValidations.role">
              <biz-remote-select v-model="providerValue[field.fieldName]" :field="field" cleared :remote-method="fetchRole" :placeholder="!field.isNull ? `[${$t('common.base.isRequire')}]${field.placeHolder}` : field.placeHolder" :computed-width-keys="['name']">
                <div class="customer-template-option" slot="option" slot-scope="{ option }">
                  <span>{{ option.name }}</span>
                </div>
              </biz-remote-select>
            </form-item>
          </template>
          <!--授权有效期-->
          <template slot="validTime" slot-scope="{ field, value }">
            <form-item ref="validTime" class="bbx-form-cell-item" :label="field.displayName" :prop-field="field" :prop-value="providerValue.validTime" :validation="extraValidations.validTime">
              <el-date-picker v-model="providerValue[field.fieldName]" type="daterange" align="right" unlink-panels range-separator="-" :start-placeholder="$t('common.base.startDate')" :end-placeholder="$t('common.base.endDate')" value-format="timestamp" :default-time="field.defaultValue ? field.defaultValue : ['00:00:00', '23:59:59']"></el-date-picker>
            </form-item>
          </template>
          <!--登录账号-->
          <template slot="loginAccount" slot-scope="{ field, value }">
            <form-item ref="loginAccount" class="bbx-form-cell-item" :label="field.displayName" :prop-field="field" :prop-value="providerValue.loginAccount" :validation="extraValidations.loginAccount">
              <form-text :field="field" v-model="providerValue[field.fieldName]" :placeholder="field.placeholder || ''" @update="update" />
            </form-item>
          </template>
          <!--登录密码-->
          <template slot="loginPassword" slot-scope="{ field, value }">
            <form-item ref="loginPassword" class="bbx-form-cell-item" :label="field.displayName" :prop-field="field" :prop-value="providerValue.loginPassword" :validation="extraValidations.loginPassword">
              <el-input type="password" show-password v-model="providerValue[field.fieldName]" autocomplete="new-password" :placeholder="!field.isNull ? `[${$t('common.base.isRequire')}]${field.placeHolder}` : field.placeHolder"></el-input>
            </form-item>
          </template>
          <!--确认密码-->
          <template slot="confirmPassword" slot-scope="{ field, value }">
            <form-item ref="confirmPassword" class="bbx-form-cell-item" :label="field.displayName" :prop-field="field" :prop-value="providerValue.confirmPassword" :validation="extraValidations.confirmPassword">
              <el-input type="password" show-password v-model="providerValue[field.fieldName]" autocomplete="new-password" :placeholder="!field.isNull ? `[${$t('common.base.isRequire')}]${field.placeHolder}` : field.placeHolder"></el-input>
            </form-item>
          </template>
        </form-builder>
      </div>
      <add-authorization-address ref="AuthorAddressRef" @updateAddress="updateAddress"></add-authorization-address>
    </div>
  </div>
</template>

<script>
/* api */
import * as serviceProviderApi from '@src/api/serviceProviderApi';
/* util */
import * as FormUtil from '@src/component/form/util';
import { safeNewDate } from '@src/util/time';
import { ValidatePassWordReg } from '@src/model/const/Reg';
import { PASS_WORD_MESSAGE } from '@src/model/const/Alert';
import { formatDate, getTimestamp, formatAddress, useFormTimezone } from 'pub-bbx-utils';
import platform from '@src/platform';
import md5 from 'js-md5';
import AddAuthorizationAddress from '../../component/AddAuthorizationAddress';
import { PageRoutesTypeEnum } from '@model/enum/PageRoutesEnum';
import { openAccurateTab } from '@src/util/platform';
import { getRootWindowInitData } from '@src/util/window';
import { TEL_REG, PHONE_REG } from '@src/util/validator';
const { disposeFormSubmitTime } = useFormTimezone();
import FormCellChange from '@src/component/compomentV2/FormCellChange/index.vue';

import { useStateNoteUserSendMessage } from '@src/modules/dept/mock.ts'
const { haveUserNote } = useStateNoteUserSendMessage()

export default {
  name: 'service-engineer-edit',
  data() {
    let extraValidations = Object.freeze({
      ifRequired: type => {
        if (['confirmPassword', 'loginAccount'].includes(type)) return true;
        let field = this.formField.find(field => field.fieldName === type);
        return !!(field && !field.isNull);
      },

      /*工程师编码*/
      engineerCode: async () => {
        let type = 'engineerCode';
        // 不需要校验
        let result = await this.checkedCode(this.providerValue[type]);
        if (!result) return (this.$refs[type].errMessage = this.$t('common.placeholder.engineerCodeRepetition'));
        if (!extraValidations.ifRequired(type)) return (this.$refs[type].errMessage = '');
        if (!this.providerValue[type]?.length) {
          return (this.$refs[type].errMessage = this.$t('common.placeholder.inputEngineerCode'));
        }
        return (this.$refs[type].errMessage = '');
      },

      /* 授权工单类型 */
      authorizeTask: () => {
        let type = 'authorizeTask';
        // 不需要校验
        if (!extraValidations.ifRequired(type)) return false;
        if (!this.providerValue[type]?.length) {
          return (this.$refs[type].errMessage = this.$t('common.placeholder.selectAuthorizationTaskType'));
        }
        return (this.$refs[type].errMessage = '');
      },
      /* 授权产品目录 */
      authorizeProduct: () => {
        let type = 'authorizeProduct';
        // 不需要校验
        if (!extraValidations.ifRequired(type)) return false;
        if (!this.providerValue[type]?.length) {
          return (this.$refs[type].errMessage = this.$t('common.placeholder.selectAuthorizationProductCatalog'));
        }
        return (this.$refs[type].errMessage = '');
      },
      /* 角色名称 */
      role: () => {
        let type = 'role';
        // 不需要校验
        if (!extraValidations.ifRequired(type)) return false;
        if (!this.providerValue[type]?.length) {
          return (this.$refs[type].errMessage = this.$t('common.placeholder.selectRole'));
        }
        return (this.$refs[type].errMessage = '');
      },
      /* 所属服务商 */
      provider: () => {
        if (this.editEngineer) return false;
        let type = 'provider';
        // 不需要校验
        if (!extraValidations.ifRequired(type)) return false;
        if (!this.providerValue[type]?.length) {
          return (this.$refs[type].errMessage = this.$t('common.placeholder.selectServiceProvider'));
        }
        return (this.$refs[type].errMessage = '');
      },
      /* 授权地址 */
      authorizeAddress: () => {
        let type = 'authorizeAddress';
        // 不需要校验
        if (!extraValidations.ifRequired(type)) return false;
        if (!this.providerValue[type]?.length) {
          return (this.$refs[type].errMessage = this.$t('common.placeholder.selectAuthorizationScope'));
        }
        return (this.$refs[type].errMessage = '');
      },
      /* 授权有效期 */
      validTime: () => {
        let type = 'validTime';
        // 不需要校验
        if (!extraValidations.ifRequired(type)) return false;
        if (!this.providerValue[type]?.length) {
          return (this.$refs[type].errMessage = this.$t('common.placeholder.selectAuthorizationIndate'));
        }
        return (this.$refs[type].errMessage = '');
      },
      /* 登录账号 */
      loginAccount: async () => {
        // 邮箱
        const EMAIL_REG = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
        if (this.editEngineer) return false;
        let type = 'loginAccount';
        let value = this.providerValue[type];
        // 不需要校验
        let result = await this.checkedLoginAccount(this.providerValue[type]);
        if (result) return (this.$refs[type].errMessage = this.$t('common.base.disableAdd'));
        if (value && ![PHONE_REG, EMAIL_REG].some(reg => reg.test(value))) return (this.$refs[type].errMessage = this.$t('common.fields.loginAccount.placeholder3'));
        if (!value?.length) {
          return (this.$refs[type].errMessage = this.$t('common.fields.loginAccount.placeholder'));
        }
        return (this.$refs[type].errMessage = '');
      },
      /* 登录密码 */
      loginPassword: () => {
        if (this.editEngineer) return false;
        let type = 'loginPassword';
        let value = this.providerValue[type];
        /* 格式校验*/
        if (value && !ValidatePassWordReg.test(value)) {
          return (this.$refs[type].errMessage = PASS_WORD_MESSAGE);
        }
        /* 登录密码更改需要校验再次输入的密码*/
        if (value !== '') {
          this.$refs.form.validate(true, 'confirmPassword');
        }
        // 不需要判空校验
        if (!extraValidations.ifRequired(type)) return false;
        /* 判空校验*/
        if (!value?.length) {
          return (this.$refs[type].errMessage = this.$t('common.fields.loginPassword.placeholder'));
        }
        return (this.$refs[type].errMessage = '');
      },
      /* 确认密码 */
      confirmPassword: () => {
        if (this.editEngineer) return false;
        let type = 'confirmPassword';
        let value = this.providerValue[type];
        if (value !== this.providerValue['loginPassword']) {
          return (this.$refs[type].errMessage = this.$t('common.validate.checkPassword'));
        }
        // 不需要判空校验
        if (!this.$refs[type]?.showRequired) return (this.$refs[type].errMessage = '');
        if (!value?.length) {
          return (this.$refs[type].errMessage = this.$t('common.placeholder.inputConfirmPassword'));
        }
        return (this.$refs[type].errMessage = '');
      },
      /* 性别 */
      sex: () => {
        let type = 'sex';
        // 不需要校验
        if (!extraValidations.ifRequired(type)) return false;
        if (!this.providerValue[type]?.length) {
          return (this.$refs[type].errMessage = this.$t('common.placeholder.selectGender'));
        }
        return (this.$refs[type].errMessage = '');
      },
    });
    return {
      id: '', // 工程师id
      tenantProviderId: '', // 租户服务商id
      formField: [],
      providerValue: {},
      address: [],
      test: [],
      disabled: false,
      extraValidations,
      loadingPage: false,
      editEngineer: false, // 是否编辑工程师
      title: '',
      oldProvider: {},
      formCellCount: 1,
      haveUserNote,
      createNeedNote:true,
    };
  },
  components: {
    AddAuthorizationAddress,
    FormCellChange,
  },
  computed: {
    showSex() {
      return !(this.providerValue['idCardType'] === '身份证' && this.providerValue['sex'] === '');
    },
    // 是否是服务商
    isProviderUser() {
      return getRootWindowInitData().isProviderUser || false;
    },
  },
  async mounted() {
    try {
      this.loadingPage = true;
      this.id = this.$getUrlObj(window).id || ''; // 工程师id
      this.tenantProviderId = this.$getUrlObj(window).tenantProviderId || ''; // 租户服务商id
      this.editEngineer = !!this.id;
      await this.getServiceManageTemplate(); // 获取工程师表单字段
      if (this.editEngineer) {
        // 工程师编辑
        this.title = this.$t('common.base.editEngineer');
        await this.getProviderDataInfo();
      } else {
        this.title = this.$t('common.base.createEngineer');
      }
    } catch (error) {
      console.warn(error);
    } finally {
      this.loadingPage = false;
    }
  },
  methods: {
    // 校验工程师编码是否重复
    async checkedCode(code) {
      try {
        let data = {
          code,
          tenantProviderId: this.tenantProviderId,
        };
        if (this.editEngineer) data.engineerId = this.id;
        let res = await serviceProviderApi.engineerCodeRepeatCheck(data);
        if (res.success) return res.result;
      } catch (e) {
        console.error(e);
      }
    },

    // 校验登录账号重复
    async checkedLoginAccount(loginName) {
      try {
        let res = await serviceProviderApi.checkEngineerPhone({ loginName });
        return !!res.error;
      } catch (e) {
        console.error(e);
      }
    },
    // 获取工程师基本信息
    async getProviderDataInfo() {
      try {
        let data = {
          tenantProviderId: this.tenantProviderId, // 租户服务商id
          id: this.id,
        };
        let res = await serviceProviderApi.getEngineerDataInfo(data);
        if (res.success && res.code === 0) {
          let result = res?.result || {};
          // 处理富文本
          result.attribute = result.formVOList;
          result = await FormUtil.initRichTextContent(this.formField, result);
          let form = this.packToForm(this.formField, result);
          this.providerValue = FormUtil.initialize(this.formField, form);
        }
      } catch (e) {
        console.error(e);
      }
    },
    // 获取新建字段
    async getServiceManageTemplate() {
      try {
        const res = this.isProviderUser && this.editEngineer ? await serviceProviderApi.searchEditEngineerConfig() : await serviceProviderApi.searchEngineerConfig();
        if (res.success) {
          const sortedFields = res.result.sort((a, b) => a.orderId - b.orderId) || [];
          if (!this.editEngineer) {
            this.formField = sortedFields.filter(item => !['status'].includes(item.fieldName));
          } else {
            this.formField = sortedFields.filter(item => !['status', 'loginPassword', 'confirmPassword', 'loginAccount'].includes(item.fieldName));
          }
          this.formField.forEach(item => {
            if (item?.setting?.maxLength) item['maxlength'] = item.setting.maxLength;
            if (item.fieldName === 'idCardAttachment') {
              // 身份证
              item.tips = this.$t('common.placeholder.imgFormat', { format: 'jpg、png、jpeg、bmp', sieze: '10M', num: '2' });
              item.accept = 'image/*';
              item.limit = 2;
            }
            if (item.fieldName === 'providerPowerOfAttorney') {
              // 授权书
              item.tips = this.$t('common.placeholder.imgFormat', { format: 'jpg、png、jpeg、bmp', sieze: '10M', num: '1' });
              item.limit = 1;
              item.accept = 'image/*';
            }
            if (item.fieldName === 'engineerQuality') item.formType = 'select'; // 工程师资质
          });
          this.providerValue = FormUtil.initialize(this.formField, {});
          // 新建服务商初始化一些字段
          this.providerValue['authorizeTask'] = [];
          this.providerValue['authorizeProduct'] = [];
          this.providerValue['authorizeAddress'] = [];
          this.providerValue['status'] = this.formField.filter(item => item.fieldName === 'status')[0]?.defaultValue;
          // 若url里面有tenantProviderId，所属服务商需要默认传过来的服务商
          if (this.tenantProviderId) this.providerValue['provider'] = await this.getProviderInfo();
        } else {
          this.$message.error(res.message);
        }
      } catch (e) {
        console.error(e);
      }
    },
    /** *********地址****************/
    addAddress(field) {
      this.$refs.AuthorAddressRef.openDialog(field.placeHolder);
    },
    removeChooseAddress(data) {
      this.providerValue['authorizeAddress'].splice(data.$index, 1);
    },
    updateAddress(val) {
      let { country = '', province = '', city = '', dist = '', address = '' } = val || {};
      let newAddress = {
        ...this.modelValue,
        country,
        province,
        city,
        dist,
        address,
      };
      this.providerValue['authorizeAddress'].push(newAddress);
    },
    /** *********地址****************/
    /* 查询工单类型 */
    async fetchTaskType(params = {}) {
      try {
        let { keyword, pageNum, pageSize } = params;
        const dataToSend = {
          keyword,
          pageNum,
          pageSize,
        };
        let res = await serviceProviderApi.searchTaskTypeList(dataToSend);
        if (!res?.result) return;
        let data = {
          total: res.result.length,
          hasNextPage: false,
        };
        data.list = this.handleTagData(res?.result);
        return data;
      } catch (error) {
        console.error('search dept error', error);
      }
    },
    /* 查询产品类型 */
    async fetchProductType(params = {}) {
      try {
        let { keyword, pageNum, pageSize } = params;
        const dataToSend = {
          keyword,
          pageNum,
          pageSize,
        };
        let res = await serviceProviderApi.searchProductTypeList(dataToSend);
        if (!res?.result?.list) return;
        let total = 1;
        if (pageNum === 1 && res?.result?.list.length === 0) {
          total = 0;
        }
        res.result.list = this.handleTagData(res.result.list);
        res.result.total = total;
        return res.result;
      } catch (error) {
        console.error('search dept error', error);
      }
    },
    /* 查询角色*/
    async fetchRole(params = {}) {
      if (!this.editEngineer && !this.providerValue?.provider.length) {
        // 如果服务商是空的话
        return this.$message({
          type: 'warning',
          message: this.$t('common.placeholder.selectProvieder'),
        });
      }
      let providerId = this.editEngineer ? this.tenantProviderId : this.providerValue?.provider?.[0]?.tenantProviderId;
      try {
        let { keyword } = params;
        const dataToSend = {
          roleName: keyword,
          providerId,
        };
        let res = await serviceProviderApi.getEngineerRole(dataToSend);
        if (!res?.data) return;
        let data = {
          // 目前角色没有分页，做成假的分页，以后接口修改直接修改这里
          total: res.data.length,
          hasNextPage: false,
        };
        data.list = this.handleTagData(res?.data);
        return data;
      } catch (error) {
        console.error('search dept error', error);
      }
    },
    updateProvider(v1) {
      if (v1?.[0]?.id !== this.oldProvider?.id) {
        this.providerValue.role = [];
      }
      this.oldProvider = v1?.[0];
    },
    /* 查询所属服务商 */
    async fetchProviderType(params = {}) {
      try {
        let { keyword, pageNum, pageSize } = params;
        const dataToSend = {
          keyword,
          pageNum,
          pageSize,
        };
        let res = await serviceProviderApi.getProviderDropDownList(dataToSend);
        if (!res?.result) return;
        res.result.list = this.handleTagData(res.result.list, 'tenantProviderId', 'providerName');
        return res.result;
      } catch (error) {
        console.error('search dept error', error);
      }
    },
    /** ****授权有效期******/
    updateValidTime(value) {
      if (Array.isArray(value) && value.length) {
        return {
          validTime: safeNewDate(value[0]).getTime(),
          inalidTime: safeNewDate(value[1]).getTime(),
        };
      }
    },
    /* 查询所属服务商 */
    async getProviderInfo() {
      try {
        let res = await serviceProviderApi.getProviderDataInfo({ tenantProviderId: this.tenantProviderId });
        if (res.success && res.code === 0 && res?.result?.providerInfoVO) {
          let item = res.result.providerInfoVO || '';
          let data =
            {
              label: (item && item.providerName) || '',
              value: (item && item.tenantProviderId.toString()) || '',
              id: (item && item.tenantProviderId.toString()) || '',
              name: (item && item.providerName) || '',
              tenantProviderId: (item && item.tenantProviderId.toString()) || '',
              code: (item && item.providerCode) || '',
            } || '';
          return [data];
        }
      } catch (e) {
        console.error(e);
      }
    },
    handleProviderData(list) {
      let tagData = list.map(item => {
        return {
          label: (item && item.name) || '',
          value: (item && item.id.toString()) || '',
          id: (item && item.tenantProviderId.toString()) || '',
          name: (item && item.name) || '',
        };
      });
      return tagData;
    },
    handleTagData(list, id = 'id', name = 'name') {
      let tagData = list.map(item => {
        let tag = {
          label: (item && item[name]) || '',
          value: (item && item[id].toString()) || '',
          id: (item && item[id].toString()) || '',
          name: (item && item[name]) || '',
        };
        if (id === 'tenantProviderId') {
          tag.tenantProviderId = (item && item.tenantProviderId) || '';
          tag.code = (item && item.providerCode) || '';
        }
        return tag;
      });
      return tagData;
    },
    update({ field, newValue, oldValue }) {
      let { fieldName, displayName, isSystem } = field;

      if (this.$appConfig.debug) {
        console.info(`[FormBuilder] ${displayName}(${fieldName}) : ${JSON.stringify(newValue)}`);
      }
      let value = this.providerValue;
      this.$set(value, fieldName, newValue);
    },
    async saveEngineer() {
      this.disabled = true;
      try {
        // 校验
        const validated = await this.$refs.form.validate();
        this.disabled = false;
        if (!validated) {
          this.$message.error(this.$t('common.validate.noNull'));
          return Promise.reject('validate fail.');
        }
        await this.submit();
      } catch (e) {
        console.error(e);
      }
    },
    async submit() {
      try {
        const submitForm = disposeFormSubmitTime(this.formField, this.providerValue); // 处理国际化日期时间数据转换
        let value = this.packSaveForm(this.formField, submitForm);
        if (this.editEngineer) {
          value.push({
            fieldName: 'loginUserId',
            displayName: '',
            value: this.id,
            valueList: [],
            isSubForm: 1,
            isSystem: 1,
            valueType: 1,
          });
        }
        let res = await serviceProviderApi.saveOrUpdateEngineerInfo({ formList: value, ...(this.haveUserNote ? {createNeedNote:this.createNeedNote} : {}) });
        platform.notification({
          type: res.success ? 'success' : 'error',
          title: res.success ? (this.editEngineer ? this.$t('serviceProvider.editEngineerSuccess') : this.$t('serviceProvider.createEngineerSuccess')) : this.editEngineer ? this.$t('serviceProvider.editEngineerFailed') : this.$t('serviceProvider.createEngineerFailed'),
          message: !res.success && res.message,
        });
        if (res.success && res.code === 0) {
          // 新建工程师成功，跳转到工程师列表页面
          this.closeAndOpenTab(PageRoutesTypeEnum.PageServiceManage);
        }
      } catch (e) {
        console.error(e);
      }
    },
    /** 将form对象转成工程师对象，用于提交表单 */
    packSaveForm(fields, form) {
      // 处理逻辑显示项
      /* 身份证附件，授权区域，授权工单类型， 授权产品目录， 授权附件上传多选*/
      const fieldArray = ['idCardAttachment', 'authorizeAddress', 'authorizeTask', 'authorizeProduct', 'providerPowerOfAttorney'];
      const type = ['user', 'attachment', 'cascader'];
      let data = JSON.parse(JSON.stringify(form));
      let formData = [];
      fields
        .filter(f => f.formType !== 'info' && f.formType !== 'separator' && f.formType !== 'autograph' && f.formType !== 'location')
        .forEach(field => {
          let { fieldName, formType, setting, isSystem, displayName } = field;
          let value = data[fieldName];
          let fieldValue = {};
          // 自定义字段
          // 人员单选
          if (formType === 'user' && !setting?.isMulti && Object.prototype.toString.call(value) === '[object Object]') {
            if (Object.keys(value).length) {
              value = value && [value];
            } else {
              value = [];
            }
          }
          // 地址
          if (formType === 'address') {
            // 转后台所需要字段
            if (value && Object.keys(value).length) {
              value.all = formatAddress(value, '');
              for (let key in value) {
                if (typeof value[key] === 'number') value[key] = value[key].toString(); // 转成字符串后后端
              }
            }
          }
          if (formType === 'authorizeAddress') {
            // 转后台所需要字段
            if (value && value.length) {
              value.forEach(item => {
                item.all = formatAddress(item, '');
              });
            }
          }
          if (fieldName === 'validTime') {
            // 授权有效期
            value = this.updateValidTime(value);
          }
          if (fieldName === 'engineerDate') {
            value = (value && safeNewDate(value).getTime()) || null;
          }
          if (fieldName === 'role') {
            // 角色
            value = value && value[0];
          }
          if (fieldName === 'provider' && !this.editEngineer) {
            // 所属服务商
            value = value && value[0];
          }
          // 密码
          if (['loginPassword', 'confirmPassword'].includes(fieldName) && !this.editEngineer) {
            // 所属服务商
            value = value && md5(value);
          }
          if (value === '') {
            value = null;
          }
          if (fieldArray.find(item => item === fieldName) || (formType === 'select' && setting?.isMulti) || type.find(item => item === formType)) {
            fieldValue = {
              displayName,
              fieldName,
              valueList: value,
              isSubForm: 0,
              isSystem,
              valueType: 2,
            };
          } else {
            fieldValue = {
              displayName,
              fieldName,
              value,
              isSubForm: 0,
              isSystem,
              valueType: 1,
            };
          }

          formData.push(fieldValue);
        });
      return formData;
    },
    /** 将工程师对象转成form表单，用于初始化表单 */
    packToForm(fields, data) {
      let engineer = {
        ...data.formVOList,
      };
      fields.forEach(field => {
        let { fieldName, isSystem } = field;
        let value = data[fieldName];
        isSystem == 1 && (engineer[fieldName] = value);
        if (fieldName === 'authorizeTask') {
          engineer.authorizeTask = [];
          if (data?.authorizeTask && data?.authorizeTask.length) {
            engineer.authorizeTask = data?.authorizeTask.map(item => {
              return {
                label: item.name,
                value: item.id,
                ...item,
              };
            });
          }
        }
        if (fieldName === 'authorizeProduct') {
          engineer.authorizeProduct = [];
          if (data?.authorizeProduct && data?.authorizeProduct.length) {
            engineer.authorizeProduct = data?.authorizeProduct.map(item => {
              return {
                label: item.name,
                value: item.id,
                ...item,
              };
            });
          }
        }
        if (fieldName === 'role') {
          engineer.role = [];
          if (data?.role) {
            engineer.role = [
              {
                value: data.role.id,
                label: data.role.name,
                ...data.role,
              },
            ];
          }
        }
        if (fieldName === 'validTime' && data?.validTime) {
          engineer.validTime = [safeNewDate(data.validTime.validTime), safeNewDate(data.validTime.inalidTime)];
        }
        if (fieldName === 'authorizeAddress' && !engineer['authorizeAddress']) {
          engineer['authorizeAddress'] = [];
        }
        if (fieldName === 'engineerDate' && data.engineerDate) {
          let newDate = getTimestamp(formatDate(data.engineerDate, 'YYYY-MM-DD'));
          engineer['engineerDate'] = newDate;
        }
      });
      return engineer;
    },
    closeAndOpenTab(type) {
      let id = window.frameElement.dataset.id;
      this.$platform.closeTab(id);

      let fromId = window.frameElement.getAttribute('id');
      // 跳转到服务商列表
      /* this.$platform.openTab({
        id: 'M_SYSTEM_547',
        title,
        url,
        reload: true,
        close: true,
        fromId
      });*/
      openAccurateTab({
        type,
        fromId,
        reload: true,
      });
    },
    cancel() {
      let id = window.frameElement.dataset.id;
      return this.$platform.closeTab(id);
    },
    handlerSex(val) {
      let idCard = val || '';
      let sex = '';
      if (idCard.length === 18) {
        sex = idCard.substring(16, 17);
      } else if (idCard.length === 15) {
        sex = idCard.substring(13, 14);
      }
      if (sex && sex % 2 === 0) sex = '女';
      else if (sex && sex % 2 === 1) sex = '男';
      return sex;
    },
  },
  watch: {
    'providerValue.idCard': {
      handler(val) {
        if (val && this.providerValue['idCardType'] === '身份证') {
          this.providerValue['sex'] = this.handlerSex(val);
        }
      },
    },
    'providerValue.idCardType': {
      // 证件类型切换时要计算性别
      handler(val) {
        if (val === '身份证') {
          this.providerValue['sex'] = this.handlerSex(this.providerValue['idCard']);
        }
      },
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-table--border {
  border: 1px solid #ebeef5 !important;
}
</style>
<style lang="scss">
@import './EngineerEditView.scss';
</style>
